﻿using JNPF.Basics.Models;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 企业号用户
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-08-13 
    /// </summary>
    public class QYUserBll
    {
        private QYUserIService service = new QYUserService();
        private QYDepartmentBll qYDepartmentBll = new QYDepartmentBll();
        private PositionBll positionBll = new PositionBll();

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<QYUserEntity>> GetList()
        {
            try
            {
                return await service.GetList();
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 同步
        /// </summary>
        /// <param name="userList">用户列表</param>
        public async Task Synchronization(List<UserEntity> userList)
        {
            var userId = UserProvider.Instance.Get().UserId;
            var config = await new SysConfigBll().GetInfo("QYHConfig");
            try
            {
                var syncList = await service.GetSyncList();
                var usersList = await service.GetList();
                #region 删除
                if (syncList.Count > 0)
                {
                    foreach (var syncUsersEntity in syncList)
                    {
                        if (userList.FindAll(u => u.Id == syncUsersEntity.UserId).Count == 0)
                        {
                            var result = new WeChatQYHelper(config.QYH_CorpId, config.QYH_CorpSecret).DeleteMember(syncUsersEntity.Id);
                            if (result == true)
                                await service.Delete(syncUsersEntity);
                        }
                    }
                }
                #endregion
                #region 创建-编辑
                if (userList.Count > 0)
                {
                    foreach (UserEntity userEntity in userList)
                    {
                        var filePath = ConfigurationKey.UserAvatarFilePath + userEntity.HeadIcon;
                        var media_id = new WeChatQYHelper(config.QYH_CorpId, config.QYH_CorpSecret).Upload(2, filePath);
                        if (syncList.FindAll(s => s.UserId == userEntity.Id).Count == 0)
                        {
                            #region 创建
                            QYMemberModel memberModel = await QYMemberModelList(userEntity, media_id);
                            var result = new WeChatQYHelper(config.QYH_CorpId, config.QYH_CorpSecret).CreateMember(memberModel);
                            if (result == true)
                            {
                                QYUserEntity syncUsersEntity = new QYUserEntity();
                                var userMergeEntity = BindModelValue(syncUsersEntity, userEntity);
                                userMergeEntity.Id = CommonHelper.Guid;
                                userMergeEntity.UserId = userEntity.Id;
                                userMergeEntity.CreateTime = DateTime.Now;
                                userMergeEntity.CreatorUserId = userId;
                                userMergeEntity.SyncState = 1;
                                await service.Create(userMergeEntity);
                            }
                            #endregion
                        }
                        else
                        {
                            #region 编辑
                            var userLastEntity = usersList.Find(o => o.Id == userEntity.Id);
                            if (userLastEntity.LastModifyTime.ToDate().ToString("yyyy-MM-dd") != "1900-01-01")
                            {
                                var syncUssers = syncList.FindAll(s => s.UserId == userEntity.Id);
                                foreach (var syncUsersEntity in syncUssers)
                                {
                                    QYMemberModel memberModel = await QYMemberModelList(userEntity, media_id);
                                    var result = new WeChatQYHelper(config.QYH_CorpId, config.QYH_CorpSecret).UpdateMember(memberModel);
                                    if (result == true)
                                    {
                                        syncUsersEntity.LastModifyUserId = userId;
                                        syncUsersEntity.LastModifyTime = userEntity.LastModifyTime;
                                        await service.Update(syncUsersEntity);
                                    }
                                }
                            }
                            #endregion
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 企业用户实体
        /// </summary>
        /// <param name="userEntity">用户实体</param>
        /// <param name="media_id">媒体文件标识</param>
        /// <returns></returns>
        private async Task<QYMemberModel> QYMemberModelList(UserEntity userEntity, string media_id)
        {
            QYMemberModel memberModel = new QYMemberModel();
            memberModel.avatar_mediaid = media_id;
            memberModel.department = Array.ConvertAll<string, long>(string.Join(",", (await qYDepartmentBll.GetListByUserId(userEntity.Id)).Select(m => m.WeChatDeptId).ToList()).Split(','), s => long.Parse(s));
            memberModel.position = string.Join(",", (await positionBll.GetListByUserId(userEntity.Id)).Select(m => m.FullName).ToList());
            memberModel.email = userEntity.Email;
            memberModel.enable = userEntity.EnabledMark.ToInt();
            memberModel.gender = userEntity.Gender.ToString();
            memberModel.mobile = userEntity.MobilePhone;
            memberModel.userid = userEntity.Id;
            memberModel.telephone = userEntity.Landline;
            memberModel.name = userEntity.RealName;
            return memberModel;
        }
        /// <summary>
        /// 将实体2的值动态赋值给实体1(名称一样的属性进行赋值)
        /// </summary>
        /// <param name="entity1">实体1</param>
        /// <param name="entity2">实体2</param>
        /// <returns>赋值后的model1</returns>
        protected T1 BindModelValue<T1, T2>(T1 entity1, T2 entity2) where T1 : class where T2 : class
        {
            Type t1 = entity1.GetType();
            Type t2 = entity2.GetType();
            PropertyInfo[] property2 = t2.GetProperties();
            //排除字段
            List<string> exclude = new List<string>() { "Id", "UserId", "CreateTime", "CreatorUserId", "SyncState" };
            foreach (PropertyInfo p in property2)
            {
                if (exclude.Contains(p.Name)) { continue; }
                t1.GetProperty(p.Name)?.SetValue(entity1, p.GetValue(entity2, null));
            }
            return entity1;
        }
    }
}
